package org.jash.shop2111.cart

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.alipay.sdk.app.PayTask
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.BaseTransientBottomBar.BaseCallback
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2111.BR
import org.jash.shop2111.R
import org.jash.shop2111.databinding.FragmentCartBinding
import org.jash.shop2111.entry.Cart
import org.jash.shop2111.entry.CartItem
import org.jash.shop2111.mvvm.BaseFragment
import org.jash.shop2111.pay.OrderInfoUtils
import org.jash.shop2111.utils.CommonAdapter
import org.jash.shop2111.utils.Event
import org.jash.shop2111.utils.MyItemAnimator
import org.jash.shop2111.utils.bus
import java.util.concurrent.Executors

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    val cart by lazy { Cart() }
    val adapter by lazy { CommonAdapter<CartItem>({R.layout.cart_item to BR.item}, cart.cartItems)}
//    var pendingDeleteId: Int = 0
    val executor = Executors.newSingleThreadExecutor()
    val handler = Handler(Looper.getMainLooper())
    override fun initData() {
        viewModel.cartsLiveData.observe(this) {
            adapter += it
            bus.postValue("setCartNumber" to it.size)
        }
        viewModel.deleteLiveData.observe(this) {
//            adapter.removeIf { it.id == pendingDeleteId }
            bus.postValue("cartNumberChange" to -1)
        }
        viewModel.loadCarts()
    }

    override fun initView() {
        binding.recycler.adapter = adapter
        binding.recycler.itemAnimator = MyItemAnimator()
        binding.recycler.itemAnimator?.addDuration = 2000
        binding.cart = cart
        binding.buy.setOnClickListener {
            executor.execute {
                val payTask = PayTask(requireActivity())
                val map = OrderInfoUtils.buildOrderParamMap(0.01f, "购买商品")
                val sign = OrderInfoUtils.getSign(map)
                val param = OrderInfoUtils.buildOrderParam(map)
                val order = "$param&$sign"
                val pay = payTask.payV2(order, true)
                Log.d("CartFragment", "initView: $pay")
                handler.post {
                    when(pay["resultStatus"]) {
                        "9000" -> Toast.makeText(requireContext(), "支付成功", Toast.LENGTH_SHORT)
                            .show()
                        else -> Toast.makeText(requireContext(), pay["memo"], Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
//        binding.all.addOnCheckedStateChangedListener { _, i -> cart.allChecked = i }
    }
    @Event("deleteCart")
    fun delete(item: CartItem) {
        val index = adapter.removeIf { it.id == item.id }
        Snackbar.make(binding.container, "删除了${item.goods_desc}.", Snackbar.LENGTH_LONG)
            .setAction("撤销") { }
            .addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    if (event == BaseCallback.DISMISS_EVENT_ACTION) {
                        adapter.add(index, item)
                    } else {
                        viewModel.deleteCart(item.id)
                    }
                }
            })
            .show()
//        MaterialAlertDialogBuilder(requireContext())
//            .setTitle("确认删除")
//            .setMessage("确定要删除${item.goods_desc}吗?")
//            .setNegativeButton("否", null)
//            .setPositiveButton("是") { _, _ ->
//                adapter.removeIf { it.id == item.id }
//            }.show()
    }

}

